﻿/// <reference path="../jquery-1.7.1.js" />

function editClick(e) {
    alert(e.target);
}

function deleteClick(e) {
    if (confirm('Вы уверены, что отите удалить этот элемент?')) {
        $(e.currentTarget).parents('.well').remove();
        //updateNameIndexes('#appInfoHide');
        var obj = $('#appInfoHide');
        var elements = [];
        $(obj).each(function () {
            elements.push(this);
        })
        for (i = 0; i <= elements.length; i++) {
            elements.eq(i).find('#iName').attr('Value', 'VALUE!!!!!!!!!!!!');
        }
    }
}

function isInt(n) {
    var intRegex = /^\d+$/;
    return intRegex.test(n)
}

function clearAddServerObjectForm() {
    $('#addServerObjectModal input').val('');
    $('#addServerObjectModal textarea').val('');
}

function updateNameIndexes(selector) {
    var elementsArray = $(selector);
    elementsArray.each(function () {
        $(this).find('#iName').attr('NEW VALUE');
    })
}

String.prototype.replaceAll = function (character, replaceChar) {
    var word = this.valueOf();

    while (word.indexOf(character) != -1)
        word = word.replace(character, replaceChar);

    return word;
}

$(document).ready(function () {

    var index = -1;
    var idNumApp = 0;

    $('#btnNotifications').click(function () {
        $('#modalNotifications').html('');
        $('#modalNotifications').dialog({
            autoOpen: false,
            height: 345,
            width: 330,
            show: { effect: "toggle", duration: 800 },
            buttons: {
                "Применить": function () {
                    $('#NotificationsUsers').append('<table class="table table-hover">');
                    
                    $("input#NotificationUserChk:checked").each(function () {
                        var id = $(this).attr('idNot');
                        var name = $(this).attr('nameNot');
                        var email = $(this).attr('emailNot');

                        $('<tr>').html(
                                    $('<td id="notId" val=' + id + '>').text(name),
                                    $('<td>').text(email)
                                ).appendTo('#NotificationsUsers');

                        //$('#NotificationsUsers').append('<tr>');
                        //    $('#NotificationsUsers').append('<td id="notId" val='+id+'>');
                        //        name;
                        //    $('#NotificationsUsers').append('</td>');
                        //    $('#NotificationsUsers').append('<td>');
                        //        email;
                        //    $('#NotificationsUsers').append('</td>');

                        //$('#NotificationsUsers').append('</tr>');
                    });
                    $('#NotificationsUsers').append('</table>');

                }
            },
            zIndex: 100000
        });
        $.ajax({
            url: "/Notifications/GetNotificationsUsers",
            type: "GET",
            success: function (data) {
                $('#modalNotifications').html(data);
            }
        })
        $('#modalNotifications').dialog('open');
    })

    $('#AddBtn').click(function () {
        index++;
        var addObject = $('#addServerObjectModal');

        var svnRevision = addObject.find('input[name="SvnRevesion"]').val();

        if (!isInt(svnRevision)) {
            alert('Номер ревизии должен быть целым числом');
            return;
        }

        var name = addObject.find('input[name="Name"]').val();
        var xml = addObject.find('textarea[name="CustomizationXml"]').val();
        var buildParameters = addObject.find('input[name="BuildParameters"]').val();
        var deployParameters = addObject.find('input[name="DeployParameters"]').val();
        var srcUrl = addObject.find('input[name="SrcUrl"]').val();
        var svnUserName = addObject.find('input[name="SvnUserName"]').val();
        var svnPassword = addObject.find('input[name="SvnUserPassword"]').val();

        //alert(xml);
        //alert(xml.replaceAll('<', '&lt;').replaceAll('>', '&gt;'));

        //return;
        var xmlValidValue = xml.replaceAll('<', '&lt;').replaceAll('>', '&gt;');
        //alert(xmlValidValue);
        //return;
        if (name == '' || xml == '' || buildParameters == '' || deployParameters == '' || srcUrl == '' || svnUserName == '') {
            alert('Пожалуйста, заполните все поля');
            return;
        }

        var appWrap = $('.app-wrap');

        var notUsers = '';
        var idx = 0;
        $('td#notId').each(function () {
           // notUsers += '<input type="text" id="iNotifications" name="ServerObjects[' + index + '].Notifications[' + idx + '] Value="' + $(this).attr('val') + '" />';         
            notUsers += $(this).attr('val') + ';';
          //  idx++;
        })
       
        var html = '<div class=well>'
            + '<div>'
                 + '<div id="appName" numApp=' + idNumApp + ' class="pull-left">'
                 + name
            + '</div>'
            + '<div class="btn-group pull-left margin-left-20">'
                 + '<div class="pull-left">'
                      + '<input type="button" class="btn btn-link" id="editApp" value="Редактировать" onclick="editClick(event);" />'
                 + '</div>'
                 + '<div class="pull-left">'
                        + '<input type="button" class="btn btn-link" id="deleteApp" value="Удалить" onclick="deleteClick(event);"/>'
                 + '</div>'
            + '</div>'
            + '<div id="appInfoHide" class="hide">'
               + '<input type="text" id="iName" name="ServerObjects[' + index + '].Name" Value="' + name + '" />'
               + '<textarea id="iCustomization" name="ServerObjects[' + index + '].CustomizationXml">' + xmlValidValue + '</textarea>'
               + '<input type="text" id="iBuildParameters" name="ServerObjects[' + index + '].BuildParameters" Value="' + buildParameters + '" />'
               + '<input type="text" id="iDeployParameters" name="ServerObjects[' + index + '].DeployParameters" Value="' + deployParameters + '" />'
               + '<input type="text" id="iSrcUrl" name="ServerObjects[' + index + '].SrcUrl" Value="' + srcUrl + '" />'
               + '<input type="text" id="iSvnUserName" name="ServerObjects[' + index + '].SvnUserName" Value="' + svnUserName + '" />'
               + '<input type="text" id="iSvnUserPassword" name="ServerObjects[' + index + '].SvnUserPassword" Value="' + svnPassword + '" />'
               + '<input type="text" id="iSvnRevision" name="ServerObjects[' + index + '].SvnRevision" Value="' + svnRevision + '" />'
               + '<input type="text" id="iNotifications" name="ServerObjects[' + index + '].Notifications" Value="' + notUsers + '" />'
        
           + '</div>'
          + '</div>'
        ;
        //+ '<input type="text" id="iCustomization" name="ServerObjects[' + index + '].CustomizationXml" Value="' + xmlValidValue + '" />'
        appWrap.append(html);

        idNumApp++;
        $('#addServerObjectModal').fadeOut(50);
    })


    $('#CloseBtn').click(function () {
        $('#addServerObjectModal').fadeOut(50);
    })

    $('#AddServerObject').click(function () {
        var addObject = $('#addServerObjectModal');
        addObject.toggle(100);
        addObject.attr('idNumApp', idNumApp);

        clearAddServerObjectForm();
    })

})
